package com.victor.modular.system.controller;

import com.victor.common.annotion.Permission;
import com.victor.common.annotion.log.BussinessLog;
import com.victor.common.constant.Dict;
import com.victor.common.constant.factory.ConstantFactory;
import com.victor.common.constant.tips.Tip;
import com.victor.common.controller.BaseController;
import com.victor.common.exception.BizExceptionEnum;
import com.victor.common.exception.BussinessException;
import com.victor.common.export.dictmap.AudienceExport;
import com.victor.common.persistence.dao.AudienceMapper;
import com.victor.common.persistence.model.Audience;
import com.victor.core.log.LogObjectHolder;
import com.victor.core.support.BeanKit;
import com.victor.core.util.ExcelReport;
import com.victor.core.util.ToolUtil;
import com.victor.modular.system.dao.AudienceCodeDao;
import com.victor.modular.system.dao.AudienceDao;
import com.victor.modular.system.service.IAudienceService;
import com.victor.modular.system.transfer.AudienceDto;
import com.victor.modular.system.transfer.FileDto;
import com.victor.modular.system.warpper.AudienceWarpper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.*;

@RequestMapping("/audience")
@Controller
public class AudienceController extends BaseController {
    private static String PREFIX = "/system/audience/";
    @Autowired
    private AudienceDao audienceDao;
    @Autowired
    private IAudienceService audienceService;
    @Autowired
    private AudienceMapper audienceMapper;
    @Autowired
    AudienceCodeDao audienceCodeDao;
    /**
     * 跳转到 观众列表页面
     */
    @RequestMapping("")
    public String index(Model model) {
        model.addAttribute("businessTypeList", ConstantFactory.me().getBusinessList());
        model.addAttribute("industryTypeList", ConstantFactory.me().getIndustryList());
        model.addAttribute("propertyList", ConstantFactory.me().getPropertyList());
        return PREFIX + "audience.html";
    }



    /**
     * 查询观众列表
     */
    @RequestMapping("/list")
    @ResponseBody
    @Permission
    public Object list(AudienceDto params) {
        List<Map<String, Object>> list = audienceDao.list(params);
        return new AudienceWarpper(list).warp();
    }
    /**
     * 跳转到修改
     */
    @RequestMapping("/audience_update/{id}")
    public String toEdit(@PathVariable Integer id, Model model) {
        Audience audience = audienceMapper.selectById(id);
        Map<String, Object> menuMap = BeanKit.beanToMap(audience);
        model.addAttribute("businessTypeList", ConstantFactory.me().getBusinessList());
        model.addAttribute("industryTypeList", ConstantFactory.me().getIndustryList());
        model.addAttribute("propertyList", ConstantFactory.me().getPropertyList());
        model.addAttribute("audience",menuMap);
        return PREFIX + "audience_edit.html";
    }
    /**
     * 跳转到新增
     */
    @RequestMapping("/audience_add")
    public String toAdd(Model model) {
        model.addAttribute("businessTypeList", ConstantFactory.me().getBusinessList());
        model.addAttribute("industryTypeList", ConstantFactory.me().getIndustryList());
        model.addAttribute("propertyList", ConstantFactory.me().getPropertyList());
        return PREFIX + "audience_add.html";
    }
    /**
     * 修改
     * @return
     */
    @RequestMapping("/edit")
    @BussinessLog(value = "修改观众",  dict = Dict.AUDIENCE_DICT)
    @Permission
    @ResponseBody
    public Tip update(AudienceDto params) {
        if(ToolUtil.isEmpty(params)){
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        LogObjectHolder.me().set(audienceMapper.selectById(params.getId()));
        audienceService.updateAudience(params);
        return SUCCESS_TIP;
    }

    /**
     * 新增
     * @return
     */
    @RequestMapping("/add")
    @BussinessLog(value = "新增观众", dict = Dict.AUDIENCE_DICT)
    @Permission
    @ResponseBody
    public Tip add(AudienceDto params) {
        audienceService.addAudience(params);
        return SUCCESS_TIP;
    }

    /**
     * 删除
     */
    @RequestMapping("/delete/{id}")
    @BussinessLog(value = "删除观众",  dict = Dict.AUDIENCE_DICT)
    @Permission
    @ResponseBody
    public Tip delete(@PathVariable Integer id) {
        if(ToolUtil.isEmpty(id)){
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        audienceService.deleteAudience(id);
        return SUCCESS_TIP;
    }
    /**
     * 批量删除
     */
    @RequestMapping("/batchDelete")
    @BussinessLog(value = "批量删除观众",  dict = Dict.AUDIENCE_DICT)
    @Permission
    @ResponseBody
    public Tip delete(@RequestParam String ids) {
        if(ToolUtil.isEmpty(ids)){
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        List<String> list = Arrays.asList(ids.split(","));
        for(String id:list){
           audienceService.deleteAudience(Integer.valueOf(id));
        }
        return SUCCESS_TIP;
    }
    /**
     * 跳转用户详情
     */
    @RequestMapping("/detail/{id}")
    public String detail(@PathVariable Integer id, Model model) {
        if (ToolUtil.isEmpty(id)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        Audience audience = this.audienceMapper.selectById(id);
        model.addAttribute(audience);
        //性别
        String sex = audience.getSex();
        String sexName = "";
        if (ToolUtil.isNotEmpty(sex)) {
            sexName = ConstantFactory.me().getSexName(Integer.valueOf(sex));
        }
        model.addAttribute("sexName", sexName);

        //商业性质1
        String businessType1 = audience.getBusinessType1();
        String businessType1Name = "";
        if (ToolUtil.isNotEmpty(businessType1)) {
            businessType1Name = ConstantFactory.me().getAudienceName(businessType1);
        }
        model.addAttribute("businessType1Name", businessType1Name);
        //商业性质2
        String businessType2 = audience.getBusinessType2();
        String businessType2Name = "";
        if (ToolUtil.isNotEmpty(businessType2)) {
            businessType2Name = ConstantFactory.me().getAudienceName(businessType1);
        }
        model.addAttribute("businessType2Name", businessType2Name);
        //商业性质3
        String businessType3 = audience.getBusinessType3();
        String businessType3Name = "";
        if (ToolUtil.isNotEmpty(businessType3)) {
            businessType3Name = ConstantFactory.me().getAudienceName(businessType1);
        }
        model.addAttribute("businessType3Name", businessType3Name);

        //行业性质
        String industryType = audience.getIndustryType();
        String industryTypeName = "";
        if (ToolUtil.isNotEmpty(industryType)) {
            industryTypeName = ConstantFactory.me().getAudienceName(industryType);
        }
        model.addAttribute("industryTypeName", industryTypeName);

        //商业性质3
        String property = audience.getProperty();
        String propertyName = "";
        if (ToolUtil.isNotEmpty(property)) {
            propertyName = ConstantFactory.me().getAudienceName(property);
        }
        model.addAttribute("propertyName", propertyName);


        //创建人
        String createUserName = "";
        Integer createUserId = audience.getCreateUserId();
        if (ToolUtil.isNotEmpty(createUserId)) {
            createUserName = ConstantFactory.me().getUserNameById(createUserId);
        }
        model.addAttribute("createUserName", createUserName);
        //修改人
        String updateUserName = "";
        Integer updateUserId = audience.getUpdateUserId();
        if (ToolUtil.isNotEmpty(updateUserId)) {
            updateUserName = ConstantFactory.me().getUserNameById(updateUserId);
        }
        model.addAttribute("updateUserName", updateUserName);
        return PREFIX + "audience_detail.html";
    }

    /**
     * 导出列表
     */
    @RequestMapping("/export")
    @Permission
    public void export(@RequestParam String fields, AudienceDto params) {
        LinkedHashMap<String, String> linkedHashMap = new AudienceExport().getDictory();
        List<String> lableList = new ArrayList<>();
        List<String> fieldList = new ArrayList<>();
        String[] fieldArr = fields.split(",");
        if (ToolUtil.isNotEmpty(linkedHashMap) && fieldArr != null && fieldArr.length > 0) {
            Iterator iter = linkedHashMap.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry<String, String> entry = (Map.Entry<String, String>) iter.next();
                String key = entry.getKey();
                String val = entry.getValue();
                if (ToolUtil.isContainWithArray(fieldArr, val)) {//如果包含选择的字段
                    fieldList.add(val);
                    lableList.add(key);
                }

            }
        }
        List<Map<String, Object>> list = audienceDao.list(params);
        list =(List)new AudienceWarpper(list).warp();
        StringBuffer sb = new StringBuffer();
        //如果当前导出字段只勾选了email邮箱或者phone手机号，那么将邮箱或者手机号拼起来导出，用“,”隔开
        if(fieldList.size()==1&&fieldList.get(0).equals("email")){
                for(Map<String, Object> map:list){
                    sb.append(map.get("email"));
                    sb.append(",");
                }
                Map<String,Object> emailMap = new HashMap<>();
                if (',' == sb.charAt(sb.length() - 1)) {
                    sb = sb.deleteCharAt(sb.length() - 1);
                }
                emailMap.put("email",sb);
                list.clear();
                list.add(emailMap);
        }
        if(fieldList.size()==1&&fieldList.get(0).equals("phone")){
            for(Map<String, Object> map:list){
                sb.append(map.get("phone"));
                sb.append(",");
            }
            Map<String,Object> emailMap = new HashMap<>();
            if (',' == sb.charAt(sb.length() - 1)) {
                sb = sb.deleteCharAt(sb.length() - 1);
            }
            emailMap.put("phone",sb);
            list.clear();
            list.add(emailMap);
        }
        ExcelReport report = new ExcelReport("观众信息", lableList.toArray(new String[lableList.size()]),
                fieldList.toArray(new String[fieldList.size()]), null, list, super.getHttpServletResponse());
        try {
            report.export();
        } catch (Exception e) {
            // e.printStackTrace();
            // TODO: handle exception
        }
    }
    /**
     * 跳转到导入
     */
    @RequestMapping("/import")
    @Permission
    public String importAudience(){
        return PREFIX + "audience_import.html";
    }
    /**
     * 批量导入验证效验
     */
    @RequestMapping("/upload")
    @ResponseBody
    public Map<String, Object> upload(@Valid FileDto fileDto, HttpServletRequest request, BindingResult result) {
        Map<String, Object> map = new HashMap<>();
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String fileName = fileDto.getFileName();
        if (ToolUtil.isEmpty(fileName)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        File tempFile = new File(victorProperties.getFileUploadTempPath() + fileName);
        if (!tempFile.exists()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        try {
            return audienceService.importAudience(request, fileDto);
        } catch (IOException e) {
            // HSSFWorkbook异常
            e.printStackTrace();
            map.put("success", false);
            return map;
        }
    }

    /**
     * 批量导入验证入库
     */
    @RequestMapping("/pushData2Base")
    @ResponseBody
    public Map<String, Object> pushData2Base(@Valid FileDto fileDto, HttpServletRequest request, BindingResult result) {
        Map<String, Object> map = new HashMap<String, Object>();
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        Object obj = request.getSession().getAttribute("AUDIENCE_IMPORT");
        if (ToolUtil.isEmpty(obj)) {
            throw new BussinessException(BizExceptionEnum.SERVER_ERROR);
        }
        try {
            audienceService.putAudience2Database(request);
            map.put("success", true);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BussinessException(BizExceptionEnum.SERVER_ERROR);
        }
        return map;
    }
}
